
#import "BRAddressPickerView.h"
#import "YQAddressAddVC.h"
#import "BRStringPickerView.h"
@interface YQAddressAddVC ()

@property (nonatomic, copy) NSArray * leftTextArr;

@property (nonatomic, strong) NSString *currentProvince;
@property (nonatomic, strong) NSString *currentCity;
@property (nonatomic, strong) NSString *currentArea;

/// 是否设为默认 0:否 1:是
//@property (nonatomic, copy) NSString *isDefault;

@property (nonatomic, copy) NSString * defaultLocale;
@property (nonatomic, copy) NSString * mobileAreaCode;

@property (nonatomic, strong) UISwitch * defaultSwitch;
@end

@implementation YQAddressAddVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self checkUserAddressApi];
}
#pragma mark - GET /api/user/address/get/{addressId}根据收货地址ID查询
- (void)checkUserAddressApi
{
    if (self.isEdit) {
        NSString *url = [NSString stringWithFormat:@"%@%@",kGET_QUERY_ADDRESS_BY_ADDRESSID_URL,self.entityModel.addressId];
        [YQPNetWorkingManager sendGetRequest:url parameters:@{} success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
            self.entityModel = [YQPAddressEntityModel mj_objectWithKeyValues:responseObject.data];
            self.leftTextArr = @[kYQLS(self.entityModel.state),
            kYQLS(self.entityModel.name),
            kYQLS(self.entityModel.userPhone),
            kYQLS(self.entityModel.city),
            kYQLS(self.entityModel.province),
            kYQLS(self.entityModel.userAddress),
            //kYQLS(@"请输入详细地址2"),
            kYQLS(self.entityModel.postalCode),
            kYQLS(@"默认地址")];
            [self.listTableView reloadData];
        } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
            
        }];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.isDefault = @"0";
    if (self.isEdit) {
        
        self.navigationItem.title = kYQLS(@"修改收货地址");
        self.rightItemTitle = kYQLS(@"修改");
    }else{
        self.leftTextArr = @[kYQLS(@"国家/地区"),
                             kYQLS(@"姓名"),
                             kYQLS(@"联系号码"),
                             kYQLS(@"城市"),
                             kYQLS(@"省份/洲"),
                             kYQLS(@"请输入详细地址"),
                             kYQLS(@"邮政编码"),
                             kYQLS(@"默认地址")];
        self.navigationItem.title = kYQLS(@"新增收货地址");
        self.rightItemTitle = kYQLS(@"新增");
    }
}

-(void)setupView {
    [super setupView];
    self.isNavShadow = YES;
    self.listTableView.backgroundColor = HexColor(0xFAFAFA);
    kYQREGISTERTABLEVIEWCELL([YQAddressAddBaseCell class])
    kYQREGISTERTABLEVIEWCELL([YQAddressAddMoreCell class])
    kYQREGISTERTABLEVIEWCELL([YQAddressAddSwitchCell class])
    //二者需一一对应
    self.defaultLocale = @"香港 852";
    self.mobileAreaCode = @"852";
}

-(void)rightItemAction:(UIButton *)sender {
    //国家
    YQAddressAddMoreCell *countryCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    if (countryCell.textField.text.length == 0) {
        [MBProgressHUD showMessage:kYQLS(@"请选择国家")];
        return;
    }
    //姓氏
//    YQAddressAddMoreCell *familyNameCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
//    if (familyNameCell.textField.text.length == 0) {
//        [MBProgressHUD showMessage:@"请输入姓氏"];
//        return;
//    }
    //名字
    YQAddressAddMoreCell *nameCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    if (nameCell.textField.text.length == 0) {
        [MBProgressHUD showMessage:kYQLS(@"请输入姓名")];
        return;
    }
    //手机
    YQAddressAddMoreCell *phoneCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    if (phoneCell.textField.text.length == 0) {
        [MBProgressHUD showMessage:kYQLS(@"请输入手机号")];
        return;
    }
    //城市
    YQAddressAddMoreCell *cityCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    if (cityCell.textField.text.length == 0) {
        [MBProgressHUD showMessage:kYQLS(@"请选择省份城市")];
        return;
    }
    //省份
    YQAddressAddMoreCell *proCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
    if (proCell.textField.text.length == 0) {
        [MBProgressHUD showMessage:kYQLS(@"请选择省份城市")];
        return;
    }
    //详细地址1
    YQAddressAddBaseCell *addressCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]];
    if (addressCell.textField.text.length == 0) {
        [MBProgressHUD showMessage:kYQLS(@"请输入详细地址")];
        return;
    }
    //详细地址2
//    YQAddressAddBaseCell *addressTwoCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:1]];
    //邮政编码
    YQAddressAddBaseCell *codeCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:1]];
    if (codeCell.textField.text.length == 0) {
        [MBProgressHUD showMessage:kYQLS(@"请输入邮政编码")];
        return;
    }
    
    NSMutableDictionary *dic = NSMutableDictionary.new;
    dic[@"state"] = countryCell.textField.text;
    if (self.isEdit) {
        dic[@"addressId"] = @(self.entityModel.addressId.intValue);
    }else{
        dic[@"addressId"] = @(1);
    }
    dic[@"city"] = cityCell.textField.text;

//    dic[@"surname"] = familyNameCell.textField.text;
//是否设为默认 0:否 1:是
    
//     = self.isDefault;

    dic[@"name"] = nameCell.textField.text;

    dic[@"postalCode"] = codeCell.textField.text;

    dic[@"province"] = proCell.textField.text;

    dic[@"userAddress"] = addressCell.textField.text;

    dic[@"userPhone"] = phoneCell.textField.text;
    NSString *url ;
    if (self.isEdit) {
        url = kPOST_UPDATE_USER_ADDRESS_URL;
    }else{
        url = kPOST_ADD_USER_ADDRESS_LIST_URL;

    }
    dic[@"isDefault"] = self.defaultSwitch.on ? @"1" : @"0";

    [YQPNetWorkingManager sendPostRequest:url parameters:dic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code == 0) {
            if (self.isEdit) {
                [MBProgressHUD showMessage:kYQLS(@"修改成功")];
            }else{
                [MBProgressHUD showMessage:kYQLS(@"添加成功")];
            }
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQUITIPSERROR(error)
    }];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    }else if (section == 1) {
        return 4;
    }else{
        return 1;
    }
    
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        YQAddressAddMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YQAddressAddMoreCell"];
        cell.isTextFieldEdit = false;
        if (indexPath.row == 0 || indexPath.row == 2) {
            if (indexPath.row == 0) {
                if (self.isEdit) {
                    cell.textField.text = self.leftTextArr[indexPath.row];
                    [cell.moreBtn setTitle:kYQLS(@"请选择") forState:(UIControlStateNormal)];
                }else{
                    cell.textField.placeholder = self.leftTextArr[indexPath.row];
                    [cell.moreBtn setTitle:kYQLS(@"请选择") forState:(UIControlStateNormal)];
                }
            }else if(indexPath.row == 2){
                cell.isTextFieldEdit = true;
                cell.moreBtn.hidden = YES;
                if (self.isEdit) {

                cell.textField.text = self.leftTextArr[indexPath.row];
                }else{
                    cell.textField.placeholder = self.leftTextArr[indexPath.row];

                }
            }else{
                if (self.isEdit) {
                    cell.textField.text = self.leftTextArr[indexPath.row];

                }else{
                    cell.textField.placeholder = self.leftTextArr[indexPath.row];

                }
            }
                [cell.moreBtn setTitle:[NSString stringWithFormat:@"+%@",self.mobileAreaCode] forState:(UIControlStateNormal)];
            
            return cell;
        }else{
            YQAddressAddBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YQAddressAddBaseCell"];
            cell.isTextFieldEdit = true;
            if(indexPath.row == 1) {
                if (self.isEdit) {
                    cell.textField.text = self.leftTextArr[indexPath.row];

                }else{
                cell.textField.placeholder = self.leftTextArr[indexPath.row];
                }
            }else{
                if (self.isEdit) {
                    cell.textField.text = self.leftTextArr[indexPath.row];

                }else{
                cell.textField.placeholder = self.leftTextArr[indexPath.row];
                }
                
            }
            return cell;
        }
    }else if (indexPath.section == 1) {
        if (indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 4) {
            YQAddressAddBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YQAddressAddBaseCell"];
            if (self.isEdit) {
                cell.textField.text = self.leftTextArr[3+indexPath.row];

            }else{
                cell.textField.placeholder = self.leftTextArr[3+indexPath.row];

            }
            cell.isTextFieldEdit = true;
            return cell;
        }else{
            YQAddressAddMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YQAddressAddMoreCell"];
            if (self.isEdit) {
                cell.textField.text = self.leftTextArr[3+indexPath.row];

            }else{
                cell.textField.placeholder = self.leftTextArr[3+indexPath.row];

            }
            cell.isTextFieldEdit = false;
            [cell.moreBtn setTitle:kYQLS(@"请选择") forState:(UIControlStateNormal)];
            return cell;
        }
    }else{
        YQAddressAddSwitchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YQAddressAddSwitchCell"];
        cell.topSwitch.on = self.entityModel.isDefault;
        cell.isTextFieldEdit = false;
        if (self.isEdit) {
            cell.textField.text = self.leftTextArr.lastObject;

        }else{
            cell.textField.placeholder = self.leftTextArr.lastObject;

        }
        
        [cell.topSwitch addTarget:self action:@selector(setUserDefaultAddressApi:) forControlEvents:UIControlEventValueChanged];
        self.defaultSwitch = cell.topSwitch;
        return cell;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 3) {
            [BRStringPickerView showStringPickerWithTitle:@"" dataSource:@[@"中国澳门 +853",@"韩国 +82",@"中国大陆 +86",@"韩国 +82",@"中国香港 +852"] defaultSelValue:@"CH" isAutoSelect:NO themeColor:kAPPThemeColor resultBlock:^(id selectValue) {
                //self.areaCode = selectValue;
                YQAddressAddMoreCell *cell = (YQAddressAddMoreCell *)[self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
                NSArray *arr = [selectValue componentsSeparatedByString:@" "];
                [cell.moreBtn setTitle:arr.lastObject forState:(UIControlStateNormal)];
                
            } cancelBlock:^{
                
            }];
        }else if (indexPath.row == 0) {
            
            ws(self);
            [AreaCodeModel getAreaCode:^(NSArray<AreaCodeModel *> * codeModelArr) {
                NSMutableArray *localeArr = [NSMutableArray array];
                NSMutableArray *localeCodeArr = [NSMutableArray array];
                for (AreaCodeModel *codeModel in codeModelArr) {
                    NSString * showTitle = [NSString stringWithFormat:@"%@ +%@",codeModel.zh,codeModel.code];
                    if ([[[ZBLocalized sharedInstance] currentLanguage] isEqualToString:@"en"]) {
                        showTitle = [NSString stringWithFormat:@"%@ +%@",codeModel.en,codeModel.code];
                    }
                    
                    
                    [localeArr addObject:showTitle];
                    [localeCodeArr addObject:codeModel.code];
                }
                
                [BRStringPickerView showStringPickerWithTitle:@"" dataSource:localeArr.copy defaultSelValue:self.defaultLocale isAutoSelect:NO themeColor:kAPPThemeColor resultBlock:^(id selectValue) {
                    self.defaultLocale = selectValue;
                    YQAddressAddMoreCell *cell = (YQAddressAddMoreCell *)[self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
                    
                    NSInteger index = [localeArr indexOfObject:selectValue];
                    AreaCodeModel *codeModel = codeModelArr[index];
                    weakself.mobileAreaCode = localeCodeArr[index];
                    cell.textField.text = codeModel.zh;
                    NSString *code = [NSString stringWithFormat:@"+%@",weakself.mobileAreaCode];
                    [cell.moreBtn setTitle:code forState:(UIControlStateNormal)];
                    //cell.leftLb.text = [NSString stringWithFormat:@"+%@",weakself.mobileAreaCode];
                    [weakself.listTableView reloadData];
                } cancelBlock:^{
                    
                }];
                
            }];
            
//            [BRStringPickerView showStringPickerWithTitle:@"" dataSource:@[@"中国澳门 +853",@"韩国 +82",@"中国大陆 +86",@"韩国 +82",@"中国香港 +852"] defaultSelValue:@"CH" isAutoSelect:NO themeColor:kAPPThemeColor resultBlock:^(id selectValue) {
//                //self.areaCode = selectValue;
//                YQAddressAddMoreCell *cell = (YQAddressAddMoreCell *)[self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
//                NSArray *arr = [selectValue componentsSeparatedByString:@" "];
//                cell.textField.text = arr.firstObject;
//
//            } cancelBlock:^{
//
//            }];
        }

    }else if (indexPath.section == 1){
        if (indexPath.row == 0 || indexPath.row == 1) {

            [BRAddressPickerView showAddressPickerWithShowType:BRAddressPickerModeArea defaultSelected:@[@"北京市", @"北京市", @"东城区"] isAutoSelect:YES themeColor:kAPPThemeColor resultBlock:^(BRProvinceModel *province, BRCityModel *city, BRAreaModel *area) {
                NSLog(@"选择的值：%@", [NSString stringWithFormat:@"%@ %@ %@", province.name, city.name, area.name]);
                self.currentProvince = province.name;
                self.currentCity = city.name;
                self.currentArea = area.name;
                YQAddressAddMoreCell *cityCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
                YQAddressAddMoreCell *proCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];

                cityCell.textField.text = [NSString stringWithFormat:@"%@", self.currentCity];
                proCell.textField.text = [NSString stringWithFormat:@"%@", self.currentProvince];
            } cancelBlock:^{
                
            }];
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001;
}
#pragma mark - 设置用户默认收货地址
- (void)setUserDefaultAddressApi:(UISwitch *)sender
{
    if (!self.isEdit) {
//        [MBProgressHUD showMessage:@"请先添加收货地址"];
        //self.isDefault = @"1";
        return;
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",kGET_SET_USER_DEFAULT_ADDRESS_URL,self.entityModel.addressId];
    [YQPNetWorkingManager sendPostRequest:url parameters:nil success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        [MBProgressHUD showMessage:responseObject.msg];
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        [MBProgressHUD showMessage:error];
    }];

}
@end
